package com.example.petstore.aspect;

import jakarta.servlet.http.HttpSession;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class LoginAdvice {

    @Pointcut("execution(* com.example.petstore.controller.UserController.accountForm(..)) ")
    public void userLoginPointcut() {}

    @Pointcut("execution(* com.example.petstore.controller.CartController.userCart(..))")
    public void userCartFormPointcut() {}

    @Around("userLoginPointcut()")
    public Object checkUserLoginChang(ProceedingJoinPoint joinPoint) throws Throwable{
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpSession session = attributes.getRequest().getSession(false);
        if (session != null && session.getAttribute("loginUser") != null) {
            Object result = joinPoint.proceed();
            return result;
        } else {
            return "user/loginByName";
            // 如果没有user，重定向到登录页面
        }
    }

    @Around("userCartFormPointcut()")
    public Object checkUserLoginCartForm(ProceedingJoinPoint joinPoint) throws Throwable{
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpSession session = attributes.getRequest().getSession(false);
        if (session != null && session.getAttribute("loginUser") != null) {
            Object result = joinPoint.proceed();
            return result;
        } else {
            return "user/loginByName";
        }
    }
}
